<?php
function ListWeather()
{
    global $dbsql;
    ImportClass('json');
    $sql_select = "select * from tblweather where iStatus=1 order by iOrder";
    $rs         = $dbsql->query($sql_select);
    $weathers   = array();
    while ( $result = $dbsql->fetch_array($rs) )
    {
        $weather       = FJSON::decode($result['cWeather'],true);
        $result['do']  = $weather['do'];
        $result['cImage'] = 'images/weather/'.$result['cImage'];
    	$weathers[]    = $result;

    }
    
    return $weathers;
}

function UpdateWeather($id=0)
{
    global $dbsql,$func_err;
	
    ImportClass('json');
    echo '<br>---------------------<br><strong>update weather</strong><br>';
    
	$sql_select= "select * from tblweather where iStatus=1 ";
	if($id>0)
    {
        $sql_select.=" and iId=$id";
    }
	$rs        = $dbsql->query($sql_select);
	
	while($result=$dbsql->fetch_array($rs))
	{
		if($result['iTimeUpdate']+(60*10) > time())continue;	
		$data  = LoadDataWeather($result['cCodeRSS']);
        
		$arr   = explode('<p>',$data);
		$arr   = explode('<br />',$arr[1]);
		$nhiettdotemp = explode('.',$arr[2]);
        $nhietdo      = explode('(',$nhiettdotemp[1]);
        
        $content= array();
        $content['status']  = $nhiettdotemp[0];
        $content['huidity'] = substr($arr[2],strpos($arr[2],"Humidity:")+10,4);
	    $content['winds']   = substr($arr[2],strpos($arr[2],"Winds:")+6);
	    $content['do']      = $nhietdo[0];
        
        $content_str            = FJSON::encode($content);
		
		if(count($arr)>0 && $content['do']!='msn')
		{
			$imgw=preg_replace("((.*)(/)(.*).gif(.*))","$3.gif",$arr[1]);
            
			$sql_update="update tblweather set
					cImage 		='".$imgw."',
					cWeather	='".$content_str."',
					iTimeUpdate	='".time()."'
					where iId=".$result['iId'];
            $rsud = $dbsql->query($sql_update);
            if($rsud)
            {
                echo $result['cCityName'].' -> '.$content['do'].'<br>';
            }else
            {
                $func_err= 'fail-update: '.$result['cCityName'].'<br>';
                echo $func_err;
                if($id>0)
                {
                    return false;
                }
            }
		}else
        {
            $func_err =  'fail-load: '.$result['cCityName'].'<br>';
            echo $func_err;
            if($id>0)
            {
                return false;
            }
        }	
	}
    return true;
}

function LoadDataWeather($code,$type='C')
{
    $file   = "http://weather.msn.com/RSS.aspx?wealocations=wc:".$code."&weadegreetype=$type";
    return file_get_contents($file);
}
?>